/**
*	客户端主js
*	来自官网：http://www.rockoa.com 
*	作者：信呼开发团队(雨中磐石)
*/

var chatobj={},windowfocus=true,jietubool=false;
var reim={
	loadtime:60*5,
	init:function(){
		CFROM = 'client';
		for(var i in tabd)this[i]=tabd[i];
		for(var i in cofst)this[i]=cofst[i];
		document.ondragover=function(e){e.preventDefault();};
        document.ondrop=function(e){e.preventDefault();};
		date = js.now('Y-m-d');
		this.loadclass('mode_dept');
		this.loadclass('mode_agent');
		nwjs.init();
		bodyunload=function(){nwjs.removetray();}
		this.resize();
		$('#leftmainlist').perfectScrollbar();
		$(window).resize(this.resize);
		this.addtabs('home','<div align="center" style="font-size:150px;color:#e8e8e8;margin-top:'+(viewheight-300)*0.5+'px"><i class="icon-comments-alt"></i></div>');
		this.initdata();
		$('#cogbtnss').click(function(){reim.showcog(this,0);return false;});
		$('#plusbtn').click(function(){reim.showcog(this,1);return false;});
		notifyobj=new notifyClass({
			title:lang('xttodo'),
			sound:'res/sound/todo.wav',
			sounderr:'',
			soundbo:this.getsound(),
			showbool:false
		});
		nwjs.createtray(document.title+'-'+adminname, 1);
		
		$(window).focus(function(){windowfocus=true;reim.winfocus();});
		$(window).blur(function(){windowfocus=false});
		this.righthistroboj = $.rockmenu({
			data:[],
			itemsclick:function(d){
				reim.rightclick(d);
			}
		});
		setInterval('reim.sInterval()',this.loadtime*1000);
		$('body').keydown(function(e){
			return reim.bodykeydown(e);
		});
		uploadobj = $.rockupload({
			inputfile:'allfileinput',
			initpdbool:false,
			updir:'{month}|reimchat',
			urlparams:{noasyn:'yes',laiyuan:'chat'},
			onchange:function(d){
				im.sendfileshow(d);
			},
			onprogress:function(f,per,evt){
				im.upprogresss(per);
			},
			onsuccess:function(f,str,o1){
				im.sendfileok(f,str);
			},
			onerror:function(str){
				js.msg('msg', str);
				im.senderror();
			}
		});
		strformat.upobj = uploadobj;
		strformat.openurl=function(url){
			reim.openurl(url);
		}
		for(var i=0;i<4;i++)if(get('lefttab'+i+''))get('lefttab'+i+'').title=lang('lefttab'+i+'');
	},
	loadclass:function(ns){
		var url = 'webmain/reim/index/'+ns+'.js';
		js.importjs(url,function(){
			var da = window[''+ns+'class']();
			for(var i in da)reim[i]=da[i];
		});
	},
	winfocus:function(){
		nwjs.jumpclear();
		im.windowfocus();
		notifyobj.close();
	},
	geturl:function(m1,a1){
		return js.apiurl(m1,a1,{'token':admintoken,'cnum':cnum,'locallang':rocklang});
	},
	ajax:function(url,das,fun,can,efun){
		var urla = url.split(',');
		if(!das)das={};
		var cans = {
			url:this.geturl(urla[0],urla[1]),data:das,
			dataType:'json',
			success:function(ret){
				js.unloading();
				if(ret.success){
					if(fun)fun(ret);
				}else{
					js.msg('msg', ret.msg);
					if(ret.code==199){
						js.msg();
						js.alert(ret.msg,function(){reim.exitlogin(true);},lang('xtexit'));
					}
					if(efun)efun(ret);
				}
			}
		};
		if(can)if(typeof(can)=='string'){cans.type=can;}else{for(var i in can)cans[i]=can[i];}
		js.ajax(cans);
	},
	delchat:function(type,sid){
		$('#lists_'+type+''+sid+'').remove();
		this.historysdata[''+type+''+sid+'']=false;
		this.ajax('reim,delchat',{type:type,sid:sid});
		this.showwaitwu();
		this.chatbadge();
	},
	sInterval:function(){
		this.initdata();
	},
	nowtime:0,
	initdata:function(){
		this.ajax('reim,clientdata',false,function(ret){
			reim.showdata(ret.data);
		});
	},
	showdata:function(ret,lxs){
		if(ret.nowtime)this.nowtime = ret.nowtime;
		if(!this.showconfigarr){
			this.showconfigarr	= ret.config;
			this.websocketlink(ret.config);
		}
		if(ret.history)this.showlishi(ret.history, lxs);
		if(ret.deptarr)this.deptarr=ret.deptarr;
		if(ret.useraarr)this.useraarr=ret.useraarr;
		if(ret.agentarr)this.agentarr=ret.agentarr;
		if(ret.grouparr)this.grouparr=ret.grouparr;
		if(ret.platsign)this.platsign=ret.platsign;
	},
	resize:function(){
		var hei = winHb();
		viewheight = hei;
		$('#leftdiv').css('height',''+hei+'px');
		$('#leftmainlist').css('height',''+(hei-60)+'px');
		$('#viewzhulist').css('height',''+hei+'px');
		
		var obj = $('div[resizeh]'),o,hei;
		for(var i=0;i<obj.length;i++){
			o = $(obj[i]);
			hei=parseInt(o.attr('resizeh'));
			o.css('height',''+(viewheight-hei)+'px');
		}
		
		//控制最小宽高
		if(nwjsgui){
			var w1 = 900,h1 = 580;
			var wid = winWb();
			var hei = winHb();
			if(wid<w1)nwjs.win.width=w1;
			if(hei<h1)nwjs.win.height=h1;
		}
	},
	
	historysdata:{},
	showhistorys:function(d,pad, lex){
		if(!d.div)d.div='leftshow0';
		var s,ty,o=$('#'+d.div+''),d1,st=d.stotal,attr;
		var num = d.num,na  = d.name;
		$('#lists_'+num+'').remove();
		this.historysdata[num]=d;
		var ops = d.optdt.substr(11,5);
		if(d.optdt.indexOf(date)!=0)ops=d.optdt.substr(5,5);
		if(!st || st<=0)st='';
		if(!d.names)d.names='';
		s	= '<div class="lists" onclick="reim.showchat(\''+num+'\')" temp="temp" id="lists_'+num+'" oncontextmenu="reim.historyright(this,event,\''+num+'\')">';
		s+='<table cellpadding="0" border="0" width="100%"><tr>';
		s+='<td style="padding-right:8px"><div style="height:34px;overflow:hidden"><img src="'+d.face+'"></div></td>';
		s+='<td align="left" width="100%"><div title="'+na+'" class="name"><font>'+na+'</font>&nbsp;'+d.names+'</div><div class="huicont">'+jm.base64decode(d.cont)+'</div></td>';
		s+='<td align="right" nowrap><span id="'+d.div+'_stotal_'+num+'" class="badge red">'+st+'</span><br><span style="color:#aaaaaa;font-size:10px">'+ops+'</span></td>';
		s+='</tr></table>';
		s+='</div>';
		if(!pad){o.append(s);}else{o.prepend(s)}
		$('#'+d.div+'_wu').remove();
	},
	historyright:function(o1,e,num){
		var d = this.historysdata[num];
		if(d.type=='user'||d.type=='company')return false
		this.rightdivobj = o1;
		var da=[];
		da.push({name:lang('open'),lx:0,num:num});
		da.push({name:lang('deljl'),lx:2,num:num});
		
		this.righthistroboj.setData(da);
		this.righthistroboj.showAt(e.clientX-3,e.clientY-3);
		return false;
	},
	rightclick:function(d){
		var da = this.historysdata[d.num];
		var o1 = $(this.rightdivobj),lx=d.lx;
		if(lx==0){
			this.rightdivobj.onclick();
		}			
		if(lx==2){
			if(d.num==this.nowtabs)this.closenowtabs();
			this.delchat(da.type,da.id);
			this.reshowwait();
		}
	},
	onoffline(id,one){
		if(one==0){
			$('#online_zixun'+id+'').remove();
			$('#online_wait'+id+'').remove();
		}
	},
	chatlabel:function(recid){
		if(!recid)return '';
		var s1 = ','+recid+',';
		if(s1.indexOf('d1')>-1)return '<span class="reimlabel">全员</span>';
		if(s1.indexOf('d')>-1)return '<span class="reimlabel1">部门</span>';
		return '';
	},
	showlishi:function(a,lxs){
		var i,len=a.length;
		for(i=0;i<len;i++){
			if(a[i].online==1)a[i].names='<span id="online_'+a[i].num+'" class="badgeonline">'+lang('online')+'</span>';
			a[i].names = this.chatlabel(a[i].receid);
			this.showhistorys(a[i],lxs);
		}
		if(this.nowtabs)$('#lists_'+this.nowtabs+'').addClass('active');
		this.chatbadge();
	},
	showwaitwu:function(){
		$('#leftshow2_wu').remove();
		var str='<div style="padding-top:50px;color:#cccccc" id="leftshow2_wu"  align="center">'+lang('zanwu')+'</div>';
		var obj = $('#leftshow2');
		if(obj.html()=='')obj.append(str);
	},
	showchatwu:function(){
		$('#leftshow0_wu').remove();
		var str='<div style="padding-top:50px;color:#cccccc" id="leftshow0_wu"  align="center"><i class="icon-comments-alt"></i> '+lang('zanw2')+'</div>';
		var obj = $('#leftshow0');
		if(obj.html()=='')obj.append(str);
	},
	reloadhist:function(d){
		var num = ''+d.type+''+d.sendid+'';
		this.ajax('reim,gethistory',{nowtime:this.nowtime},function(ret){
			reim.showdata(ret.data, true);
			try{chatobj[num].recedata()}catch(e){}
		});
		if(d.type=='chehui'){
			$('#qipaocont_mess_'+d.messid+'').html(jm.base64decode(d.mess));
			return;
		}
		var sopenfun=function(b){
			notifyobj.close();
			reim.showchat(b.num);
			return false;
		}
		if(!windowfocus){
			notifyobj.showpopup(jm.base64decode(d.mess),{
				icon:d.face,
				num:num,
				title:jm.base64decode(d.title),
				click:function(b){
					return sopenfun(b);
				}
			});
			nwjs.jumpicon();
		}
	},
	reloadwait:function(d){
		js.alertclose();
		this.ajax('reim,gewait',{kfuid:d.kfuid},function(ret){
			reim.showdata(ret.data);
		});
		if(d.mess){
			nwjs.jumpicon();
			notifyobj.showpopup(jm.base64decode(d.mess),{
				title:jm.base64decode(d.title),
				sound:'res/sound/jias.wav',
				icon:d.face,
				click:function(b){
					return false;
				}
			});
		}
	},
	
	yidu:function(type,sid){
		this.ajax('reim,yidu',{type:type,sid:sid});
		this.chatbadge();
	},
	yidus:function(type,sid){
		var num=''+type+''+sid+'';
		var spid = 'leftshow0_stotal_'+num+'';
		$('#'+spid+'').html('');
		this.chatbadge();
	},
	showchat:function(num){
		var d = this.historysdata[num];
		if(!d)return;
		if(d.type=='zixun' || d.type=='uchat' || d.type=='achat' || d.type=='agroup' || d.type=='agent'){
			var spid = 'leftshow0_stotal_'+num+'',stt=$('#'+spid+'').html();
			$('#'+spid+'').html('');
			var bo = this.addtabs(''+num+'','webmain/reim/index/zye_chat_yuan.html?num='+num+'');
			try{if(bo)chatobj[num].onshow(stt);}catch(e){}
			this.chatbadge();
		}
		if(d.type=='company'){
			js.confirm(lang('qielons',d.name),function(jg){
				if(jg=='yes'){
					js.loading(lang('qielong'));
					js.location('?d=reim&cnum='+d.dwnum+'');
				}
			});
		}
	},
	reshowwait:function(){
		var obj = $('div[id^="lists_wait"]');
		var len = obj.length;
		if(len==0)len='';
		$('#waitbadge').html(len);
	},
	chatbadge:function(){
		var obj = $('span[id^="leftshow0_stotal_"]');
		var len = obj.length,sto=0,i,s1;
		for(i=0;i<len;i++){
			s1 = obj[i].innerHTML;
			if(!s1)s1=0;
			sto+=parseInt(s1);
		}
		if(sto==0)sto='';
		$('#chatbadge').html(sto);
		this.showchatwu();
	},
	showcog:function(o1,lx){
		if(!this.cogmenu)this.cogmenu =$.rockmenu({
			data:[],
			width:120,
			itemsclick:function(d){
				reim.clickcogclick(d);
			}
		});
		var d = [];
		if(lx==0){
			d.push({'name':lang('reload'),lx:'sx'});
			if(admintype=='1')d.push({'name':lang('htgl'),lx:'huo'});
			d.push({'name':lang('huifuguan'),lx:'huifu'});
			d.push({'name':lang('editpass'),lx:'pass'});
			d.push({'name':lang('appdeng'),lx:'app'});
		}
		d.push({'name':lang('qiehuan'),lx:'qie'});
		d.push({'name':lang('createchat'),lx:'chat'});
		if(lx==0)d.push({'name':lang('exit'),lx:'exit'});
		this.cogmenu.setData(d);
		var off = $(o1).offset();
		if(lx==0)this.cogmenu.showAt(60,off.top+d.length*36);
		if(lx==1)this.cogmenu.showAt(off.left+10, off.top+10);
	},
	clickcogclick:function(d){
		var lx=d.lx;
		if(lx=='sx'){
			js.loading(lang('sxing'));
			js.reload();
		}
		if(lx=='exit'){
			this.exitlogin();
		}
		if(lx=='huo'){
			reim.openurl(''+NOWURL+'?m=index&d=manage&cnum='+cnum+'');
		}
		if(lx=='pass'){
			this.addtabs('editpass','webmain/reim/index/zye_editpass.html?num=editpass');
		}
		if(lx=='huifu'){
			this.addtabs('huifuguan','webmain/reim/index/zye_huifuguan.html?num=huifuguan');
		}
		if(lx=='qie'){
			this.addtabs('companyqie','webmain/reim/index/zye_company.html?num=company');
		}
		if(lx=='chat'){
			this.createchat();
		}
		if(lx=='app'){
			this.dengapp();
		}
	},
	dengapp:function(){
		js.alert('<div align="center" ><img src="images/logo.png" id="ewmsrc" height="150" width="150"><br>'+lang('appmsg1')+'</div>',false,lang('appmsg2'));
		js.resizetan('alert');
		var url = this.geturl('index','loginewm')+'&rand='+js.getrand()+'';
		get('ewmsrc').src=url;
	},
	exitlogin:function(bo){
		if(!bo){js.confirm(lang('qudtc'),function(jg){if(jg=='yes')reim.exitlogin(true)});return;}
		js.loading(lang('tczon'));
		this.ajax('login,exit',false,function(){
			js.setoption('lgautodl', '');
			js.location('?m=login&&d=reim&tform=main');
		});
	},
	backemts:function(s){
		chatobj[this.nowtabs].addinput(s);
		$('#aemtsdiv').hide();
	},
	bodykeydown:function(e){
		var code	= e.keyCode;
		if(code==27){
			if($.imgviewclose())return false;
			if(get('alert_main')){
				js.tanclose('alert');
			}else{
				this.closenowtabs();
			}
			return false;
		}
	}
}

var tabd={
	nowtabs:'',
	addtabs:function(num, nr){
		var ids = 'tabs_'+num+'',bo,s;
		if(!get(ids)){
			if(nr.substr(0,7)=='webmain'){
				var urlpms= '',ura=nr.split('?'),i;
				if(ura[1]){
					var nusa = ura[1].split('&');
					for(i=0;i<nusa.length;i++){
						var nus	= nusa[i].split('=');
						urlpms += ",'"+nus[0]+"':'"+nus[1]+"'";
					}
					if(urlpms!='')urlpms = urlpms.substr(1);
				}
				s = '<div tabs="'+num+'" id="'+ids+'"><div style="padding:20px"><img src="images/mloading.gif"></div></div>';
				var rand = js.getrand();
				$.get(nr+'&rand='+rand+'',function(da){
					var s1 = da;
						s1 = s1.replace(/\{rand\}/gi, rand);
						s1 = s1.replace(/\{params\}/gi, "var params={"+urlpms+"};");
					$('#'+ids+'').html(s1);
					reim.resize();
				});
			}else{
				s = '<div tabs="'+num+'" id="'+ids+'">'+nr+'</div>';
			}
			$('#viewzhulist').append(s);
			bo = false;
		}else{
			bo = true;
		}
		this.showtabs(num);
		return bo;
	},
	closetabs:function(num){
		var ids = 'tabs_'+num+'';
		$('#'+ids+'').remove();
		var ood = $('#viewzhulist div[tabs]:last');
		var snu = ood.attr('tabs');
		this.showtabs(snu);
	},
	closenowtabs:function(){
		if(this.nowtabs && this.nowtabs!='home')this.closetabs(this.nowtabs);
	},
	showtabs:function(num){
		$('div[tabs]').hide();
		var ids = 'tabs_'+num+'';
		$('#'+ids+'').show();
		$('div[temp]').removeClass('active');
		$('#lists_'+num+'').addClass('active');
		this.nowtabs = num;
	},
	changleft:function(oi){
		$('div[ltabs="left"]').removeClass('leftactive');
		$('#leftmenu'+oi+'').addClass('leftactive');
		$('div[ltabs="cont"]').hide();
		$('#leftshow'+oi+'').show();
		if(oi==1)this.showdept();
		if(oi==3)this.showagent();
	}
}
var cofst={
	websocketlink:function(a){
		if(this.connectbool){
			this.serverstatus(1);
			return false;
		}
		if(!a){
			this.serverstatus(3);
			return false;
		}
	
		var wsurl = jm.base64decode(a.wsurl),receid = a.recid;
		this.showconfigarr = a;
		if(isempt(wsurl) || wsurl.indexOf('ws')<0){
			this.serverstatus(3);
			return false;
		}
		clearTimeout(this.relianshotime_time);
		websocketobj = new websocketClass({
			adminid:adminid,
			reimfrom:receid,
			wshost:wsurl,
			sendname:adminname,
			onerror:function(o,ws){
				reim.connectbool=false;
				reim.serverstatus(0);
				js.msg('msg',''+lang('wflia')+'<br><span id="lianmiaoshoetime"></span><a href="javascript:;" onclick="reim.connectservers()">['+lang('clixn')+']</a>',0);
				reim.relianshotime(30);
			},
			onmessage:function(str){
				reim.connectbool=true;
				clearTimeout(reim.relianshotime_time);
				var a=js.decode(str);
				reim.receivemesb(a);
			},
			onopen:function(){
				reim.connectbool=true;
				reim.serverstatus(1);
				clearTimeout(reim.relianshotime_time);
				js.msg('none');
			},
			onclose:function(o,e){
				reim.connectbool=false;
				if(reim.otherlogin)return;
				reim.serverstatus(0);
				js.msg('msg',''+lang('wfli2')+'<br><span id="lianmiaoshoetime"></span><a href="javascript:;" onclick="reim.connectservers()">['+lang('clixn')+']</a>',0);
				reim.relianshotime(10);
			}
		});
	},
	connectservers:function(){
		if(this.connectbool){
			this.serverstatus(1);
			return;
		}
		var bo = this.websocketlink(this.showconfigarr);
		if(bo)js.msg('wait',lang('linking'));
	},
	serverstatus:function(lx){
		
	},
	relianshotime:function(oi){
		clearTimeout(this.relianshotime_time);
		$('#lianmiaoshoetime').html('('+oi+''+lang('mssex')+')');
		if(oi<=0){
			this.connectservers();
		}else{
			this.relianshotime_time=setTimeout('reim.relianshotime('+(oi-1)+')',1000);
		}
	},
	//服务端发消息调用opener.reim.serversend(a);
	serversend:function(a){
		if(!this.connectbool)return false;
		websocketobj.send(a);
		return true;
	},
	//获取在线人员
	getonline:function(){
		this.serversend({'atype':'getonline'});
	},
	
	//别的地方登录
	otherlogins:function(){
		this.otherlogin = true;
		var msg=lang('bdfad');
		js.alert(msg);
		this.serverstatus(2);
	},
	
	receivemesb:function(d){
		var lx=d.type,sendid=d.adminid;
		if(lx=='offoline'){
			this.otherlogins();
			return;
		}
		if(lx=='uchat' || lx=='achat' || lx=='agroup' || lx=='zixun' || lx=='agent' || lx=='chehui'){
			this.reloadhist(d);
		}
		if(lx=='rewait'){
			if(d.sendid!=adminid)this.reloadwait(d);
		}
		if(lx=='zxoff'){
			this.onoffline(d.zixunid,0);
		}
	},
	getsound:function(){
		var lx = js.getoption('soundcog'),chs=false;
		if(lx=='')lx='1';
		if(lx==1)chs=true;
		return chs;
	},
	setsound:function(o1){
		var lx=(o1.checked)?'1':'2';
		js.setoption('soundcog', lx);
		notifyobj.setsound(o1.checked);
	},
	getzhuom:function(){
		var lx = js.getoption('zhuomcog'),chs=false;
		if(lx=='')lx='1';
		if(lx==1)chs=true;
		return chs;
	},
	setzhuom:function(o1){
		var lx=(o1.checked)?'1':'2';
		js.setoption('zhuomcog', lx);
	},
	openurl:function(url,lx,ism){
		if(lx==1 && this.platsign){
			var jg=(url.indexOf('?')>0) ? '&':'?';
			url += ''+jg+'platsign='+this.platsign+''; 
		}
		var w=1000,h=550;
		if(ism){
			w=380;
			js.open(url,w,h);
			return;
		}
		if(!nwjsgui){
			window.open(url);
		}else{
			js.open(url,w,h);
		}
	}
}

var im = {
	clickqipao:function(o1,e){
		
	},
	rightqipao:function(o1,e,rnd){
		chatobj[reim.nowtabs].rightqipao(o1,e,rnd);
	},
	backemts:function(s){
		chatobj[reim.nowtabs].addinput(s);
		$('#aemtsdiv').hide();
	},
	sendfileshow:function(f){
		var num = uploadobj.nownum;
		chatobj[num].sendfileshow(f);
	},
	upprogresss:function(per){
		var num = uploadobj.nownum;
		strformat.upprogresss(per);
	},
	sendfileok:function(f,str){
		var num = uploadobj.nownum;
		chatobj[num].sendfileok(f, str);
	},
	senderror:function(){
		var num = uploadobj.nownum;
		chatobj[num].senderrornss();
	},
	readclip:function(num,e){
		chatobj[num].readclip(e);
	},
	upbase64:function(nuid){
		var o = get('jietuimg_'+nuid+'');
		chatobj[reim.nowtabs].sendbase64(o.src);
	},
	cropScreen:function(){
		if(nwjsgui){
			var oatg = nwjs.getpath();
			nw.Shell.openItem(''+oatg+'/images/reimcaptScreen.exe');
		}
	},
	windowfocus:function(){
		if(jietubool){
			chatobj[reim.nowtabs].pasteimg(true);
		}
		jietubool = false;
	},
	fileyulan:function(pn,fid){
	}
}